package com.leetcode.problems052;

import java.util.ArrayList;
import java.util.List;

/**
 * https://leetcode-cn.com/problems/n-queens-ii/
 * @Date 2021/12/09 14:34
 * @Author ghery
 * @Version V1.0
 */
public class Solution {

    private boolean[] cols = null;

    private boolean[] leftDia = null;

    private boolean[] rightDia = null;

    public int totalNQueens(int n) {
        cols = new boolean[n];
        //左对角线（下标：col - row + n - 1）
        leftDia = new boolean[2 * n - 1];
        //右对角线（下标：col + row）
        rightDia = new boolean[2 * n - 1];
        List<Integer> res = new ArrayList<>();
        List<List<Integer>> ans = new ArrayList<>();
        solveNQueens(0,n,n,res,ans);
        return ans.size();
    }

    private void solveNQueens(int row,int n,int q,List<Integer> res,List<List<Integer>> ans){
        if(q == 0){
            ans.add(new ArrayList<>(res));
            return;
        }
        if(row == n){
            return;
        }
        for (int i = 0; i < n; i++) {
            if(cols[i] || leftDia[i - row + n - 1] || rightDia[row + i]){
                continue;
            }
            cols[i] = true;
            leftDia[i - row + n - 1] = true;
            rightDia[row + i] = true;
            res.add(i);
            solveNQueens(row + 1,n,q - 1,res,ans);
            res.remove(res.size() - 1);
            cols[i] = false;
            leftDia[i - row + n - 1] = false;
            rightDia[row + i] = false;
        }
    }



    public static void main(String[] args) {
        int n = 1;
        System.out.println(new Solution().totalNQueens(8));
    }
}
